--[[
  General purpose static resource scanner.
  Scans a directory recursively and build a list
  of available resources matching the specified filter.
  The filter is simply defined as a set of file extensions to keep,
  in the following format : "jpg,png,wav,mid,mp3" (example).
  The result is a list of resources defined as a tuple :
  (key, fullpath) with primary key "key".

  Example :
    Given the resource tree in the filesystem :
    root/images/01.png
                02.png
         sound/ping.wav
               noise.wav
         music/ballad.mp3
               scherzo.mid

    Then running the scanner on the "root" directory returns
    the following list of tuples :

    ("01", "root/images/01.png")
    ("02", "root/images/02.png")
    ("ping", "root/sound/ping.wav")
    ("noise", "root/sound/noise.wav")
    ("ballad", "root/music/ballad.mp3")
    ("scherzo", "root/music/scherzo.mid")

    As you can see, the limitation is that any collision on the primary key
    "key" will override existing values.

    You should never have 2 files with the same name in different directories,
    no matter if the extensions differ, for instance "path/to/01.png" and
    "other/path/to/01.wav" will collide with the same primary key "01".

    So be careful to name the resources accordingly.
--]]

dofile("dir_tree_itr.luax")

filter = {"png", "jpg", "wav", "mp3" }

function print_name(name)
  print("Hello, "..name.." !")
end

-- returns the 'basename' and the 'basedir' 
function getBases(filename)
    return  string.gsub(filename, "(.*/)(.*)", "%2") or filename,
            string.gsub(filename, "(.*/)(.*)", "%1")
end

function getKeyAndExtension(basename)
    return string.gsub(basename, "([^.]*)\.(.*)", "%1"),
           string.gsub(basename, "([^.]*)\.(.*)", "%2")
end

function scan_resources(dir)
  
  resource_list={}

  for filename, attr in dirtree(dir) do
    -- We treat only files.
    if attr.mode == "file" then
      -- Retrieve basename and basedir.
      basename, basedir = getBases(filename)
      -- Retrieve the extension.
      key, extension = getKeyAndExtension(basename)
      matches="no"
      -- Check that the entry matches the extension filter.
      for k,filter_ext in ipairs(filter) do
        if (extension == filter_ext) then
          matches="yes"
          break
        end
      end
      -- Keep only entries which match.
      if matches == "yes" then
        -- Add a new resource in the list.
        -- resource_list[#resource_list+1] = {key, extension, filename}
        resource_list[key] = filename
      end
    end
  end

  return resource_list

end

